<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 订单
 */
class Order extends CT_Controller
{

    public function __construct()
    {
        parent::__construct();
        
        $this->load->model('course_cate_model');
        $this->load->model('course_list_model');
        $this->load->model('course_package_model');
        $this->load->model('order_model');
        $this->load->model('nursery_model');
        $this->load->model('area_model');
        $this->load->model('city_model');
        
        $this->lang->load('error', 'chinese');
    }
    
    /**
     * 首页
     */
    public function pay()
    {
        $this->session->unset_userdata('order_not_repeat');
        
        //课包信息
        $cp_id = intval($this->input->get('cp_id', TRUE));
        if (!$cp_id){
            redirect('/');
        }
        
        $conditions = array('id'=>$cp_id, 'status'=>1);
        $fields = '*';
        $cp_info = $this->course_package_model->find($conditions,$fields);
        if(!$cp_info){
            redirect('/');
        }
        $data['cp_info'] = $cp_info;
        
        if($cp_info['type']!=1){
            $conditions = array('member_id'=>$this->_uid,'course_package_id'=>$cp_id, 
                                'nursery_id'=>$this->_nursery_id,'status in(1,5)'=>NULL);
            $fields = 'id';
            $order_info = $this->order_model->find($conditions,$fields);
            
            if($order_info){
                $this->ct_template->write('_title', '错误提示');
                $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>'该体验课包只能购买一次' ), FALSE);
                $this->ct_template->render();
                return;
            }
        }
        
        //园所信息
        $nursery_id = $this->_nursery_id;
        $conditions = array('id'=>$nursery_id, 'status'=>1);
        $fields = '*';
        $nursery_info = $this->nursery_model->find($conditions,$fields);
        if(!$nursery_info){
            redirect('/');
        }
        $data['nursery_info'] = $nursery_info;
        
        /*
        //地区信息
        $conditions = array('id'=>$nursery_info['area_id'], 'status'=>1);
        $fields = '*';
        $area_info = $this->area_model->find($conditions,$fields);
        if(!$area_info){
            redirect('/');
        }
        $data['area_info'] = $area_info;
        
        //市区信息
        $conditions = array('id'=>$nursery_info['city_id'], 'status'=>1);
        $fields = '*';
        $city_info = $this->city_model->find($conditions,$fields);
        if(!$city_info){
            redirect('/');
        }
        $data['city_info'] = $city_info;
        */
        
        $this->ct_template->write('_title', '确认购买');
        $this->ct_template->write_view('content', 'order/pay', $data, FALSE);
        $this->ct_template->render();
    }
    
    /**
     * 待支付状态立即支付
     */
    public function go_pay()
    {
        try {
            $order_id = $this->input->get('order_id', TRUE);
            if (!$order_id){
                throw new Exception('订单编号为空');
            }
            $order_id = id_decode($order_id);
            
            //订单信息
            $conditions = array('id'=>$order_id, 'status'=>0);
            $fields = '*';
            $order_info = $this->order_model->find($conditions,$fields);
            if(!$order_info){
                throw new Exception('订单不存在');
            }
            $data['order_info'] = $order_info;
            
            //课包信息
            $conditions = array('id'=>$order_info['course_package_id'], 'status'=>1);
            $fields = '*';
            $cp_info = $this->course_package_model->find($conditions,$fields);
            if(!$cp_info){
                throw new Exception('订单对应课包不存在');
            }
            $data['cp_info'] = $cp_info;
        
            //园所信息
            $conditions = array('id'=>$order_info['nursery_id'], 'status'=>1);
            $fields = '*';
            $nursery_info = $this->nursery_model->find($conditions,$fields);
            if(!$nursery_info){
                throw new Exception('订单对应园所不存在');
            }
            $data['nursery_info'] = $nursery_info;
        
            /*
            //地区信息
            $conditions = array('id'=>$nursery_info['area_id'], 'status'=>1);
            $fields = '*';
            $area_info = $this->area_model->find($conditions,$fields);
            if(!$area_info){
                redirect('/');
            }
            $data['area_info'] = $area_info;
        
            //市区信息
            $conditions = array('id'=>$nursery_info['city_id'], 'status'=>1);
            $fields = '*';
            $city_info = $this->city_model->find($conditions,$fields);
            if(!$city_info){
                redirect('/');
            }
            $data['city_info'] = $city_info;
            */
        
            $this->ct_template->write('_title', '确认购买');
            $this->ct_template->write_view('content', 'order/go_pay', $data, FALSE);
            $this->ct_template->render();
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
    }
    
    /**
     * 微信JS支付
     */
    public function weixin_wap_go_pay()
    {
        //判断用户是否登陆
        $this->load->library('CT_auth_member_teacher');
        if(!$this->_uid || !$this->_nursery_id){
            echo json_encode(array('code' => 'E_504', 'msg' => $this->lang->line('E_504')));
            exit;
        }
    
        $order_id = $this->input->post('order_id', true);
        if (!$order_id) {
            echo json_encode(array('code' => 'E_400', 'msg' => $this->lang->line('E_400')));
            exit;
        }
        
        //订单信息
        $conditions = array('id'=>id_decode($order_id), 'status'=>0);
        $fields = '*';
        $order_info = $this->order_model->find($conditions,$fields);
        if(!$order_info){
            echo json_encode(array('code' => 'E_503', 'msg' => $this->lang->line('E_503')));
            exit;
        }
    
        //获取课包信息
        $cp_info = $this->course_package_model->find(array('id'=>$order_info['course_package_id'],'status'=>1));
        if(!$cp_info){
            echo json_encode(array('code' => 'E_503', 'msg' => $this->lang->line('E_503')));
            exit;
        }
    
        require_once (APPPATH . "/third_party/wechat/wxpay/lib/WxPay.Api.php");
        require_once (APPPATH . "/third_party/wechat/wxpay/lib/WxPay.JsApiPay.php");
        $tools = new JsApiPay();
        $openId = $this->_open_id;
    
        //付款金额
        $total_fee = $order_info['pay_fee']  * 100;
        //商户网站订单系统中唯一订单号，必填
        $out_trade_no = 'd' . $order_id;
        //订单名称
        $subject = "叮咚老师购买" . $total_fee . '元-' . $cp_info['title'];
    
        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($subject);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 24 * 3600));
        $input->SetNotify_url(DOMAIN_MAIN . '/order/weixin_notify');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        var_dump($order);
        exit;
    
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $jsApiParameters = json_decode($jsApiParameters, true);
    
        echo json_encode(array('code' => 'E_200', 'msg' => $jsApiParameters, 'out_trade_no' => $out_trade_no));
    
    }

    /**
     * 微信JS支付
     */
    public function weixin_wap_pay()
    { 
        //判断用户是否登陆
        $this->load->library('CT_auth_member_teacher');
        if(!$this->_uid || !$this->_nursery_id){
            echo json_encode(array('code' => 'E_504', 'msg' => $this->lang->line('E_504')));
            exit;
        }
        
        $cp_id = intval($this->input->post_int('cp_id', true));
        $pay_type = intval($this->input->post_int('pay_type', true));
        $buy_num = intval($this->input->post('buy_num', true));
        if (!$cp_id || !$pay_type || !$buy_num) {
            echo json_encode(array('code' => 'E_400', 'msg' => $this->lang->line('E_400')));
            exit;
        }
        
        //获取课包信息
        $cp_info = $this->course_package_model->find(array('id'=>$cp_id,'status'=>1));
        if(!$cp_info){
            echo json_encode(array('code' => 'E_503', 'msg' => $this->lang->line('E_503')));
            exit;
        }
        
        //获取课包列表信息
        $cl_info = $this->course_list_model->find(array('id'=>$cp_info['course_list_id'],'status'=>1));
        if(!$cl_info){
            echo json_encode(array('code' => 'E_503', 'msg' => $this->lang->line('E_503')));
            exit;
        }
        
        //防重复提交
        $flag = $this->session->userdata('order_not_repeat');
        
        if($flag ){
            $order_id = $flag;
        }else{
            $data = array(
                'member_id' => $this->_uid,
                'nursery_id' => $this->_nursery_id,
                'course_cate_id' => $cl_info['course_cate_id'],
                'course_list_id' => $cp_info['course_list_id'],
                'course_package_id' => $cp_id,
                'course_package_num'=>$buy_num,
                'pay_fee' => $cp_info['sale_price']*$buy_num,
                'pay_way' => $pay_type,
                'pay_ip' => $this->input->ip_address(),
                'hours' => ($cp_info['hours']+$cp_info['give_hours'])*$buy_num,
                'give_hours' => $cp_info['give_hours']*$buy_num,
                'package_hours' => $cp_info['hours']*$buy_num,
                'surplus_hours'=>$cp_info['hours']*$buy_num,
                'create_date' => date('Y-m-d H:i:s'),
                'update_date' => date('Y-m-d H:i:s'),
                'expiry_date' => $cp_info['expiry_date'],
            );
        
            $order_id = $this->order_model->insert($data);
        
            $this->session->set_userdata('order_not_repeat', $order_id);
        }
        
        if($pay_type == 2){//划课支付
            //更新订单
            $order_columns = array('status'=>3, 'pay_time'=>date('Y-m-d H:i:s'), 'update_date'=>date('Y-m-d H:i:s'));
            $this->order_model->update($order_columns,array('id'=>$order_id));
            
            echo json_encode(array('code' => 'E_1000', 'msg' => 'ok', 'out_trade_no' => id_encode($order_id)));
            exit;
        }
        
        /*
        if($pay_type == 1){//微信支付
            //更新订单
            $order_columns = array('status'=>1, 'pay_time'=>date('Y-m-d H:i:s'), 'update_date'=>date('Y-m-d H:i:s'));
            $this->order_model->update($order_columns,array('id'=>$order_id));
            
            //递加course_cate表sales字段
            $this->course_cate_model->update_sales($cl_info['course_cate_id']);
            
            echo json_encode(array('code' => 'E_1000', 'msg' => 'ok', 'out_trade_no' => id_encode($order_id)));
            exit;
        }
        */
        
        require_once (APPPATH . "/third_party/wechat/wxpay/lib/WxPay.Api.php");
        require_once (APPPATH . "/third_party/wechat/wxpay/lib/WxPay.JsApiPay.php");
        $tools = new JsApiPay();
        $openId = $this->_open_id;
        
        //付款金额
//         $total_fee = $cp_info['sale_price'] * $buy_num * 100;
        $total_fee = 1;
        //商户网站订单系统中唯一订单号，必填
        $out_trade_no = 'd' . id_encode($order_id);
        //订单名称
        $subject = "叮咚老师购买" . $total_fee . '元-' . $cp_info['title'];
        
        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($subject);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 24 * 3600));
        $input->SetNotify_url(DOMAIN_MAIN . '/order/weixin_notify');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
      
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $jsApiParameters = json_decode($jsApiParameters, true);
        
        echo json_encode(array('code' => 'E_200', 'msg' => $jsApiParameters, 'out_trade_no' => $out_trade_no));
        
    }
    
    public function pay_success($order_id = 0) {
        header("Content-Type:text/html;charset=utf-8");
    
        if (!$order_id) {
            exit($this->lang->line('E_400'));
        }
    
        $this->load->model('order_model');
        $order_info = $this->order_model->find(array('id' => id_decode($order_id)));
        if (!$order_info) {
            exit($this->lang->line('E_100018'));
        }
        
        //园所信息
        $conditions = array('id'=>$order_info['nursery_id'], 'status'=>1);
        $fields = '*';
        $nursery_info = $this->nursery_model->find($conditions,$fields);
        if(!$nursery_info){
            exit($this->lang->line('E_503'));
        }
        $order_info['nursery_info'] = $nursery_info;
    
        $this->ct_template->write('_title', '支付成功');
        $this->ct_template->write_view('content', 'order/success', $order_info, FALSE);
        $this->ct_template->render();
       
        
    }
    
    /**
     * 微信异步通知页面
     */
    public function weixin_notify() {
    
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        $doc = new DOMDocument();
        $doc->loadXML($data);
    
        $transaction_id = $doc->getElementsByTagName("transaction_id")->item(0)->nodeValue;
    
        if ($transaction_id) {
            //验证订单真实性
            if (!$this->_wexin_queryorder($transaction_id)) {
                file_put_contents(APPPATH.'logs/weixin_error.log', date('Y-m-d H:i:s') . " ". $data. "\n", FILE_APPEND);
//                 echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
                echo 'fail';
            } else {
                try {
                    file_put_contents(APPPATH.'/logs/weixin_notify.log', date('Y-m-d H:i:s') . " ". $data. "\n", FILE_APPEND);
                    //商户订单号
                    $out_trade_no = $doc->getElementsByTagName("out_trade_no")->item(0)->nodeValue;
                    $trade_status = $doc->getElementsByTagName("result_code")->item(0)->nodeValue;
    
                    if ($trade_status == 'SUCCESS') {                       //支付成功
                        if ($out_trade_no) {
                            $payment_id = id_decode(substr($out_trade_no, 1));
                            $payment_info = $this->order_model->find(array('id' => $payment_id));
    
                            if (!empty($payment_info)) {    //如果存在订单号
                                if ($payment_info['status'] != 1) {

                                    //更新订单
                                    $order_columns = array('transaction_id'=>$transaction_id, 'status'=>1, 'pay_time'=>date('Y-m-d H:i:s'), 'update_date'=>date('Y-m-d H:i:s'));
                                    $this->order_model->update($order_columns,array('id'=>$payment_id));
                                    
                                    //递加course_cate表sales字段
                                    $this->course_cate_model->update_sales($payment_info['course_cate_id']);
    
                                } 
                                
//                                 echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                                echo 'success';
                            } else {
//                                 echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
                                echo 'fail';
                            }
                        } else {
//                             echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
                            echo 'fail';
                        }
                    } else {
//                         echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
                        echo 'fail';
                    }
                } catch (Exception $ex) {
                    file_put_contents(APPPATH.'logs/weixin_error.log', date('Y-m-d H:i:s') . " ". $data. "\n", FILE_APPEND);
//                     echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
                    echo 'fail';
                }
            }
        } else {
            file_put_contents(APPPATH.'logs/weixin_error.log', date('Y-m-d H:i:s') . " ". $data. "\n", FILE_APPEND);
//             echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
            echo 'fail';
        }
    }
    
    /**
     * 微信同步通知页面
     */
    public function weixin_return() {
        header("Content-type:text/html;charset=utf-8");
        $trade_status = $this->input->get('result');
    
        if ($trade_status == 'ok') {
            $payment_id = $this->input->get('out_trade_no');
            //验证订单真实性
            if (!$this->_wexin_queryorder(null, $payment_id) ) {
                exit($this->lang->line('E_100012'));
            }
            if ($payment_id) {
                $payment_id = id_decode(substr($payment_id, 1));
                $payment_info = $this->order_model->find(array('id' => $payment_id));
    
                if (!empty($payment_info)) {
                    if ($payment_info['status'] == 1) {
                        redirect('/order/pay_success/' . id_encode($payment_id));
                    }
                    
                    //更新订单
                    $order_columns = array('status'=>1, 'pay_time'=>date('Y-m-d H:i:s'), 'update_date'=>date('Y-m-d H:i:s'));
                    $this->order_model->update($order_columns,array('id'=>$payment_id));
                    
                    //递加course_cate表sales字段
                    $this->course_cate_model->update_sales($payment_info['course_cate_id']);
                    
                    redirect('/order/pay_success/' . id_encode($payment_id));
                    
                } else {
                    exit($this->lang->line('E_100018'));
                }
            } else {
                exit($this->lang->line('E_400'));
            }
        } else {
            exit($this->lang->line('E_100012'));
        }
    }
    
    /**
     * 微信查询订单
     */
    private function _wexin_queryorder($transaction_id = null, $out_trade_no = null) {
        require_once(APPPATH . "/third_party/wechat/wxpay/lib/WxPay.Api.php");
    
        $input = new WxPayOrderQuery();
        if ($transaction_id) {
            $input->SetTransaction_id($transaction_id);
        }
        if ($out_trade_no) {
            $input->SetOut_trade_no($out_trade_no);
        }
    
        $result = WxPayApi::orderQuery($input);
    
        if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"
            && array_key_exists("trade_state", $result) && $result["trade_state"] == "SUCCESS") {
                return true;
            }
    
            return false;
    }


}
